<template>
  <div>
    即时通讯组件
    <!--        <h2>{{data}}</h2>-->
    <div id="main" style="width: 700px;height: 450px"></div>
  </div>
</template>

<script>
import echarts from "echarts";

export default {
  name: "TestWebSocket",
  data() {
    return {
      websocket: "",
      data: []
    };
  },
  created() {
    this.$nextTick(() => {
      this.initWebSocket();
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.echartsData();
    });
  },
  beforeRouteLeave(to, from, next) {
    if (this.websocket) {
      this.websocket.close();
    }
    next();
  },
  watch: {
    data: function(newVal) {
      this.EChcrts();
      console.log("新数据--" + newVal);
    }
  },
  methods: {
    initWebSocket() {
      //var socket_data;
      if ("WebSocket" in window) {
        this.websocket = new WebSocket("ws://localhost:8082/websocket1");
      } else {
        console.log("bu_zhi_chi");
      }
      this.websocket.onopen = function(event) {
        console.log("client");
      };
      this.websocket.onmessage = function(event) {
        let data = JSON.parse(event.data);
        func1(data);
      };
      let func2 = function func3(val) {
        //在此处即可同时使用websocket的数据和data数据，method函数
        this.data = val;
      };
      let func1 = func2.bind(this);
    },
    async echartsData() {
      const result = await this.$http.get("echartsData");

      if (1 !== result.data.code) {
        return this.$message.error("获取数据失败！");
      }
      this.data = result.data.data;
    },
    EChcrts() {
      this.myChart = echarts.init(document.getElementById("main"));
      let option = {
        title: {
          text: "图表展示"
        },
        tooltip: {},
        legend: {
          data: ["完成数量"]
        },
        xAxis: {
          data: ["轴承", "轮对", "磁粉探伤", "磨合实验", "注油机", "轴颈测量"]
        },
        yAxis: {},
        series: [
          {
            name: "完成数量",
            type: "bar",
            data: this.data
          }
        ]
      };
      this.myChart.setOption(option);
    }
  }
};
</script>

<style scoped>
</style>